$(function(){
    $('#swoole-page').height(window.screen.height * 0.8);

    /**
     * 1: 前端无操作，一分钟后会自动断开(网上说要维持心跳包)
     */
    var swoole_page = new Vue({
        el: "#swoole-page",
        data: {
            websocket: undefined,
            message: '',
            user_id: 0,
            heart_beat_id: '',
            friend_id: 0,
        },
        mounted: function() {
            this.initSwoole();
        },
        methods: {
            getCurrentTimeStr: function() {
                var date = new Date();//当前时间
                var month = date.getMonth() + 1;  // 月
                var day = date.getDate();         // 日
                var hour = date.getHours();       // 时
                var minute = date.getMinutes();   // 分
                var second = date.getSeconds();   // 秒
                return  date.getFullYear() + '-' + month + '-' + day
                    + " " + hour + ':' + minute + ':' + second;
            },
            // 开始心跳
            startHeartBeat: function() {
                this.heart_beat_id = setInterval(function () {
                    var data = {
                        type: 1,
                        content: '',
                        user_id: swoole_page.user_id
                    };
                    swoole_page.websocket.send(JSON.stringify(data))
                }, 55000);
            },
            // 结束心跳
            endHeartBeat: function() {
                if (this.heart_beat_id) {
                    clearInterval(this.heart_beat_id);
                }
            },
            // 弹窗提示
            responseUser: function(message, type = 'error') {
                new NoticeJs({
                    // timeout: 1000,// 秒级别
                    text: message,
                    position: 'topCenter',
                    type: type,
                    modal: true,
                    animation: {
                        open: 'animated bounceInRight',
                        close: 'animated bounceOutLeft'
                    }
                }).show();
            },
            // 验证是否为空
            verifyEmpty: function(value) {
                if(value === undefined) { // 只能用 === 运算来测试某个值是否是未定义的
                    return false;
                }
                if(value == null) { // 等同于 value === undefined || value === null
                    return false;
                }
                // String
                if(value == "" || value == null || value == undefined){ // "",null,undefined
                    return false;
                }
                if (!value) { // "",null,undefined,NaN
                    return false;
                }
                if(!$.trim(value)){ // "",null,undefined
                    return false;
                }
                // Array
                if(value.length == 0){ // "",[]
                    return false;
                }
                if(!value.length){ // "",[]
                    return false;
                }
                // Object {}
                if ($.isEmptyObject(value)){ // 普通对象使用 for...in 判断，有 key 即为 false
                    return false;
                }
                return true;
            },
            // 初始化用户
            initialUser: function() {
                var data = {type: 2, content: this.message, user_id: this.user_id};
                this.websocket.send(JSON.stringify(data));
            },
            // 连接用户
            matchFriend: function() {
                if (this.websocket == undefined) {
                    this.responseUser('swoole连接不存在，无法发送消息');
                    return false;
                }
                var data = {type: 4, content: '', user_id: this.user_id};
                this.websocket.send(JSON.stringify(data));
            },
            // 断开连接用户
            disconnectFriend: function() {
                if (this.websocket == undefined) {
                    this.responseUser('swoole连接不存在，无法发送消息');
                    return false;
                }
                var data = {type: 5, content: '', user_id: this.user_id};
                this.websocket.send(JSON.stringify(data));
            },
            // 初始化连接
            initSwoole: function () {
                var wsServer = 'ws://swoole.lincanming.xyz/';
                this.websocket = new WebSocket(wsServer);
                this.websocket.onopen = function (evt) {
                    swoole_page.startHeartBeat();
                    swoole_page.initialUser();
                    console.log('连接swoole成功' + new Date());
                    swoole_page.responseUser('连接swoole成功', 'success');
                };

                // 关闭连接
                this.websocket.onclose = function (evt) {
                    swoole_page.endHeartBeat();
                    console.log('断开swoole连接' + new Date());
                    swoole_page.responseUser('断开swoole连接');
                };

                // 接受消息
                this.websocket.onmessage = function (evt) {
                    try {
                        var obj = JSON.parse(evt.data);
                        if (typeof obj === 'object' && obj) {
                            switch (obj.type) {
                                case 1:// 心跳数据
                                    console.log('心跳消息');
                                    break;
                                case 2:// 系统消息
                                    if ('userId' in obj) {
                                        if (obj.userId == true) {
                                            swoole_page.friend_id = true;
                                        } else {
                                            swoole_page.friend_id = false;
                                        }
                                    }

                                    swoole_page.formatHintMessage(obj.content);
                                    break;
                                case 3:// 朋友消息
                                    swoole_page.formatFriendMessage(obj.content);
                                    break;
                            }
                        }
                    } catch (error) {
                        console.log(evt.data);
                    }
                };

                // 连接失败的提示
                this.websocket.onerror = function (evt, e) {
                    swoole_page.endHeartBeat();
                };
            },
            // 样式化自己的消息体
            formatSelfMessage: function(message) {
                this.sendTimeMessage();
                var str = '<div class="self-message">'
                    + '<div class="self-nickname"><div class="self-nickname-body">自己</div></div>'
                    + '<div class="self-message-body">'
                    + message +
                    '</div></div>'
                $('#window').append(str);
                var window_target = document.getElementById("window");
                window_target.scrollTop = window_target.scrollHeight + 500;
            },
            // 样式化对方的消息体
            formatFriendMessage: function(message) {
                this.sendTimeMessage();
                var str = '<div class="friend-message">'
                    + '<div class="friend-nickname"><div class="friend-nickname-body">陌生人</div></div>'
                    + '<div class="friend-message-body">'
                    + message
                    + '</div></div>'
                $('#window').append(str);
            },
            // 样式化提示信息
            formatHintMessage: function(message) {
                this.sendTimeMessage();
                $('#window').append('<div class="hint-message"><div class="hint-message-body">系统消息: ' + message + '</div></div>');
            },
            // 发送时间消息
            sendTimeMessage: function() {
                $('#window').append('<div class="hint-message"><div class="hint-message-body">' + this.getCurrentTimeStr() + '</div></div>');
            },
            // 发送消息
            swooleSend: function () {
                if (this.websocket == undefined) {
                    this.responseUser('swoole连接不存在，无法发送消息');
                    return false;
                }

                if (this.friend_id == 0) {
                    this.responseUser('您当前无聊天好友');
                    return false;
                }

                if (this.verifyEmpty(this.message) === false) {
                    this.responseUser('内容不能为空');
                    return false;
                }

                var data = {type: 3, content: this.message, user_id: this.friend_id};
                this.websocket.send(JSON.stringify(data));
                this.formatSelfMessage(this.message);
                this.message = '';
            }
        }
    });
});
